// src/api/ad.ts
import type { AxiosRequestConfig } from 'axios'
import { request, USE_MOCK } from './request'

/* -------------------- 类型定义 -------------------- */
export type AdType = 'platform' | 'business'
export type AdPosition = 'carousel' | 'fixed1' | 'fixed2' | 'fixed3' | 'fixed4' | 'fixed5'
export type AdStatus = 'enabled' | 'disabled'

export interface Ad {
  id: number
  type: AdType
  position: AdPosition
  title: string
  image: string
  link?: string
  status: AdStatus
  createdAt: string
}

/* -------------------- mock 数据 -------------------- */
let mockAds: Ad[] = [
  {
    id: 1,
    type: 'platform',
    position: 'carousel',
    title: '首页轮播广告',
    image: '/mock/banner1.png',
    link: 'https://example.com',
    status: 'enabled',
    createdAt: '2025-09-01'
  },
  {
    id: 2,
    type: 'business',
    position: 'fixed1',
    title: '商家广告位1',
    image: '/mock/ad1.png',
    status: 'disabled',
    createdAt: '2025-09-05'
  }
]

/* -------------------- API 方法 -------------------- */

/**
 * 获取广告列表
 */
export async function getAds(config?: AxiosRequestConfig): Promise<Ad[]> {
  if (USE_MOCK) {
    return Promise.resolve(mockAds)
  }
  return request<Ad[]>({
    url: '/ads',
    method: 'GET',
    ...config
  })
}

/**
 * 新增广告
 */
export async function addAd(ad: Omit<Ad, 'id' | 'createdAt'>): Promise<Ad> {
  if (USE_MOCK) {
    const newAd: Ad = {
      ...ad,
      id: Date.now(),
      createdAt: new Date().toISOString()
    }
    mockAds.push(newAd)
    return Promise.resolve(newAd)
  }
  return request<Ad>({
    url: '/ads',
    method: 'POST',
    data: ad
  })
}

/**
 * 更新广告
 */
export async function updateAd(id: number, ad: Partial<Ad>): Promise<Ad> {
  if (USE_MOCK) {
    mockAds = mockAds.map(item => (item.id === id ? { ...item, ...ad } : item))
    const updated = mockAds.find(item => item.id === id)!
    return Promise.resolve(updated)
  }
  return request<Ad>({
    url: `/ads/${id}`,
    method: 'PUT',
    data: ad
  })
}

/**
 * 删除广告
 */
export async function deleteAd(id: number): Promise<void> {
  if (USE_MOCK) {
    mockAds = mockAds.filter(item => item.id !== id)
    return Promise.resolve()
  }
  return request<void>({
    url: `/ads/${id}`,
    method: 'DELETE'
  })
}
